package com.mall.seckill.controller;

import com.mall.common.util.RespResult;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Darren
 * @date 2022-10-19 11:25
 * Description：
 */
@RestController
@RequestMapping("/lock")
public class RedissonLockTest {
    @Autowired
    private RedissonClient redissonClient;

    @Value("${server.port}")
    private String port;

    @GetMapping("/test")
    public RespResult lockTest() throws InterruptedException {
        // 获取锁
        RLock lock = redissonClient.getLock("No001");
        lock.lock();

        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        System.out.println(port + "获取锁:" + dateFormat.format(new Date()));
        TimeUnit.SECONDS.sleep(5);
        System.out.println(port + "释放锁:" + dateFormat.format(new Date()));

        // 释放锁
        lock.unlock();
        return RespResult.ok(port);
    }
}
